package com.example.chatonline.controller;

import com.example.chatonline.pojo.Result;
import com.example.chatonline.pojo.UserDto;
import com.example.chatonline.repository.UserRepository;
import com.example.chatonline.service.UserService;
import com.example.chatonline.utils.JwtUtils;
import io.jsonwebtoken.JwtBuilder;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private JwtUtils jwtUtils;


    @PostMapping("/register")
    public Result register(@RequestBody UserDto userDto){
           boolean exists = userService.register(userDto);
        if(exists){
            return Result.error();
        }else
        {
        return Result.success();
        }
    }

    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto){
        if(userService.login(userDto)){
            String token = jwtUtils.generateJwtToken(userDto.getUserName());
            Result<String> success = Result.success(token);
            return success;
        }
        return Result.error();
    }

}
